package com.wnhz.work.yz.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.adapter.BathAdapter;
import com.wnhz.work.yz.adapter.ItemPopChooseAdapter;
import com.wnhz.work.yz.bean.BathroomDetailBean;
import com.wnhz.work.yz.bean.ClassifyChildBean;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.GoodsListBean;
import com.wnhz.work.yz.bean.ItemChooseBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.adapterview.PullListView;
import com.wnhz.work.yz.view.adapterview.core.PullToRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ---家居馆列表
 */
public class BathActivity extends BaseActivity implements View.OnClickListener, TabLayout.OnTabSelectedListener, AdapterView.OnItemClickListener {
    private TextView title, tv_number;
    private ImageView iv_right;

    private List<ClassifyChildBean> nameList = new ArrayList<>();

    private TabLayout myTabLayout;
    private PullListView my_listView;
    private List<GoodsListBean> beanList = new ArrayList<>();
    private List<GoodsListBean> beanList2 = new ArrayList<>();

    private BathAdapter bathAdapter;
    private int index = 0;
    private ImageView iv_right_img;
    private boolean isTrue;
    private TextView tv_top;
    private View all_view;
    private String titles;
    private String cateId;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Finish1 event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bath);
        // MyApplication.getInstance().addDestoryActivity(this, "bath");
        EventBus.getDefault().register(this);
        initData();
        initView();
    }

    private void initData() {
        titles = getIntent().getStringExtra("titles");
        cateId = getIntent().getStringExtra("cateId");
    }

    private void initView() {
        //
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText(titles);
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.btn_main_right).setVisibility(View.VISIBLE);
        //   findViewById(R.id.btn_main_right).setOnClickListener(this);
        iv_right = (ImageView) findViewById(R.id.view_main_right_image);
        iv_right.setImageResource(R.mipmap.ic_gouwuche_li);
        iv_right.setOnClickListener(this);
        iv_right.setVisibility(View.VISIBLE);
        tv_number = (TextView) findViewById(R.id.tv_number);//小红点
        //  tv_number.setVisibility(View.VISIBLE);
        findViewById(R.id.rl_right).setOnClickListener(this);
        iv_right_img = (ImageView) findViewById(R.id.iv_right_img);
        tv_top = (TextView) findViewById(R.id.tv_top);
        all_view = findViewById(R.id.all_view);

        myTabLayout = (TabLayout) findViewById(R.id.myTabLayout);
        my_listView = (PullListView) findViewById(R.id.my_listView);


        myTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        myTabLayout.setOnTabSelectedListener(this);

        bathAdapter = new BathAdapter(this, beanList2);
        my_listView.getListView().setAdapter(bathAdapter);
        my_listView.getListView().setOnItemClickListener(this);
        upload();
        my_listView.setLoadDataListener(new PullToRefreshLayout.LoadDataListener() {
            @Override
            //下拉刷新调用
            public void onRefresh() {
                beanList2.clear();
                indexPage = 1;
                uploadGoods(indexPage, true);
            }

            @Override
            //下拉加载更多调用
            public void onLoadMore() {
                //模拟1秒的时间加载数据
                uploadGoods(++indexPage, false);
            }
        });
    }


    /**
     * 模拟加载数据
     *
     * @param needFresh 是否需要刷新清空数据还是继续增加数据
     */
    public void loadDate(final boolean needFresh) {

        //刷新，则清空数据
        if (needFresh) {
            beanList2.clear();
        }
        if (beanList == null || beanList.size() <= 0) {
            MyToast("没有更多了!");
        }
        for (int i = 0; i < beanList.size(); i++) {
            beanList2.add(beanList.get(i));
        }
        //将新数据全部加入
        bathAdapter.notifyDataSetChanged();
        //是否需要更新和是否还有更多内容
        my_listView.onLoadComplete(needFresh, true);

    }

    private int indexPage = 1;

    private void uploadGoods(int page, final boolean isClean) {

        String token="";
        if(MyApplication.getInstance().getUserBean()!=null && MyApplication.getInstance().getUserBean().getToken()!=null && !MyApplication.getInstance().getUserBean().getToken().equals("")){
            token=MyApplication.getInstance().getUserBean().getToken();
        }
        //  showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("cateId", caId);
        map.put("page", page);
        XUtil.Post(Url.GOODS_GETCATEINFO, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: page1cc" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
//                    if ("-1".equals(res)) {
//                        //info = "请重新登录";
//                        MyToast("请重新登录");
//                        startActivity(new Intent(BathActivity.this, LoginNewActivity.class));
//                        return;
//                    }
                    JSONArray jsonArray = jsonObject.optJSONArray("info");
                    if (jsonArray != null) {
                        beanList.clear();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            GoodsListBean bean = new GoodsListBean();
                            Gson gson = new Gson();
                            bean = gson.fromJson(jsonArray.optString(i), GoodsListBean.class);
                            beanList.add(bean);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                // closeDialog();
                loadDate(isClean);
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //  closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private static final String TAG = "BathActivity";

    private void upload() {
        //  showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("cateId", cateId);
        Log.i(TAG, "initData: cateId" + cateId);
        XUtil.Post(Url.GOODS_GETCHILDCATE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                // closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: cateId" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
//                    if ("-1".equals(res)) {
//                        //info = "请重新登录";
//                        MyToast("请重新登录");
//                        startActivity(new Intent(BathActivity.this, LoginNewActivity.class));
//                        return;
//                    }

                    JSONArray jsonArray = jsonObject.optJSONArray("info");
                    if (jsonArray != null) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            ClassifyChildBean bean = new ClassifyChildBean();
                            JSONObject j = jsonArray.getJSONObject(i);
                            String cateId = j.optString("cateId");
                            String title = j.optString("title");

                            bean.setCateId(cateId);
                            bean.setTitle(title);

                            nameList.add(bean);

                            ItemChooseBean bean1 = new ItemChooseBean();
                            bean1.setClicked(false);
                            bean1.setTitles(title);
                            types.add(bean1);
                        }
                    }
                    for (int i = 0; i < nameList.size(); i++) {
                        if(myTabLayout==null || myTabLayout.newTab()==null ||nameList==null || nameList.get(i)==null ||nameList.get(i).getTitle()==null || nameList.get(i).getCateId()==null){
                        }else {
                            myTabLayout.addTab(myTabLayout.newTab().setText(nameList.get(i).getTitle()).setTag(nameList.get(i).getCateId()));

                        }
                    }
                    bathAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            case R.id.rl_right:
                isTrue = !isTrue;
                if (isTrue) {
                    ObjectAnimator.ofFloat(iv_right_img, "rotation", 0.0f, 180.0f).setDuration(300).start();
                    showSelectPop(v);
                    tv_top.setVisibility(View.VISIBLE);
                    all_view.setVisibility(View.VISIBLE);
                    isTrue = true;
                } else {
                    dismiss();
                }
                break;
            case R.id.view_main_right_image:
//                MyApplication.getInstance().destoryActivity("bath");
//                MyApplication.getInstance().destoryActivity("search");
                EventBus.getDefault().post(new Finish1());
                EventBus.getDefault().post(new BathroomDetailBean());
                finish();
                break;
            default:
                break;
        }
    }

    private String caId;

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        caId = (String) tab.getTag();
        Log.i(TAG, "onTabSelected: caId" + caId);
        indexPage = 1;
        beanList2.clear();
        uploadGoods(indexPage, true);
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }


    private PopupWindow popWindow;
    private WindowManager.LayoutParams lp;
    private List<ItemChooseBean> types = new ArrayList<>();


    private void showSelectPop(View v) {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_choose, null);
        final GridView grid = (GridView) view.findViewById(R.id.gv_pop_choose);

        final ItemPopChooseAdapter itemPopChooseAdapter = new ItemPopChooseAdapter(this, types);
        grid.setAdapter(itemPopChooseAdapter);

        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String chooseText = types.get(position).getTitles();//选中的条目

                int size = types.size();
                for (int i = 0; i < size; i++) {
                    if (i == position) {
                        types.get(i).setClicked(true);
                        myTabLayout.setScrollPosition(position, 0, true);
                        caId = nameList.get(position).getCateId();
                        Log.i(TAG, "onTabSelected: caId1" + caId);
                        indexPage = 1;
                        beanList2.clear();
                        uploadGoods(indexPage, true);

                    } else {
                        types.get(i).setClicked(false);
                    }
                }
                itemPopChooseAdapter.notifyDataSetChanged();

                popWindow.dismiss();
            }
        });

        popWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
               /* WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);*/

                dismiss();
            }
        });

        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);
        // 设置好参数之后再show
        popWindow.showAsDropDown(v);

       /* //变暗屏幕
        lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);*/
    }

    private void dismiss() {
        if (null != popWindow) {
            ObjectAnimator.ofFloat(iv_right_img, "rotation", 180.0f, 360.0f).setDuration(300).start();
            tv_top.setVisibility(View.GONE);
            all_view.setVisibility(View.GONE);
            isTrue = false;
            popWindow.dismiss();
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, ShoppingDetailsActivity.class);
        intent.putExtra("goodsId", beanList2.get(position).getGoodsId());
        Log.e(TAG, "onItemClick:goodsId " + beanList2.get(position).getGoodsId());
        startActivity(intent);
    }
}
